package com.vsclouds.mp.config.springmvc;

import com.vsclouds.mp.config.global.HandlerInterceptorImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * Created with Software Dept.
 * <p>
 * User: tian
 * Date: 2018-07-30
 * Time: 12:22
 * Description:
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private HandlerInterceptorImpl handlerInterceptor;

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 设置默认跨域配置,默认跨域预请求结果缓存30分钟
        corsConfiguration.applyPermitDefaultValues();
        // 增加跨域允许的请求方法支持
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.OPTIONS.name(), HttpMethod.GET.name(), HttpMethod.DELETE.name(),
                HttpMethod.POST.name(), HttpMethod.PUT.name(), HttpMethod.HEAD.name()));
        corsConfiguration.addAllowedOrigin("http://develop.vsclouds.com");
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", corsConfiguration.applyPermitDefaultValues());
        CorsFilter corsFilter = new CorsFilter(configurationSource);
        return new FilterRegistrationBean(corsFilter);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将所有/static/** 访问都映射到classpath:/static/ 目录下
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        HandlerInterceptorImpl handlerInterceptor = new HandlerInterceptorImpl();
//        handlerInterceptor.setRedisTemplate(redisTemplate);
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
}
